<template>
  <div class="views-container">

    <el-card
      shadow="none"
      style="margin-top:1rem"
    >
      <div
        shadow="none"
      >
        <el-form
          :model="form"
          :label-position="'left'"
        >
          <el-form-item label="选择大数据集群：">
            <el-select
              v-model="form.cmFlag"
              placeholder="选择集群"
              class="filter-item"
              @change="selectCm()"
            >
              <el-option
                v-for="item in form.cmList"
                :key="item.cmFlag"
                :label="item.cmName"
                :value="item.cmFlag"
              />
            </el-select>
          </el-form-item>

          <!-- <el-form-item label="选择大数据子集群：">
            <el-select v-model="form.clusterFlag" size="small" placeholder="选择子集群" class="filter-item"
              @change="childrenClu">
              <el-option v-for="item in form.clusterList" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item> -->
          <!-- <el-form-item
            label="选择服务类型:"
            style="display: block;"
          >
            <div>
              <el-checkbox-group
                v-model="typeList"
                style="display: flex;flex-wrap:wrap"
              >
                <el-checkbox
                  v-for="item in typeData"
                  :key="item"
                  :label="item"
                />

              </el-checkbox-group>
            </div>
          </el-form-item> -->
        </el-form>

        <!-- <el-button
          type="primary"
          @click="checkType"
        >
          查看图例
        </el-button> -->
      </div>

      <el-card
        shadow="none"
        style="margin-top:0.6rem"
      >
        <div class="title-row">异常实时显示</div>
        <div style="display:grid;grid-template-columns: repeat(5,1fr);">
          <div
            v-for="item in clustData"
            :key="item.name"
            style="display: flex;align-items: center;justify-content: center;"
          >
            <div class="cardBox">
              <div :class="item.value > 1 ? 'error' : item.value > 0 ? 'warn' : 'total'">
                <i
                  v-if="item.value > 1"
                  class="el-icon-circle-close"
                />
                <i
                  v-else-if="item.value == 0"
                  class="el-icon-circle-check"
                />
                <i
                  v-else
                  class="el-icon-warning-outline"
                />
              </div>
              {{ item.name }}
            </div>
            <div />
          </div>
        </div>
      </el-card>
    </el-card>
    <!-- <el-card style="width:100%;margin-top:5px">
      <div
        class="title-row"
        style="padding:10px"
      >
        <span class="title-row-bar" />服务状态监控
      </div>
      <el-form
        :inline="true"
        size="small"
        label-width="220px"
      >
        <el-form-item label="查询时间:">
          <el-date-picker
            v-model="serviceValue"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00','23:59:59']"
            :picker-options="pickerOptions"
            @change="serviceChange"
          />
        </el-form-item>
      </el-form>
      <div
        id="service"
        style="width:100%;height:270px"
      />
    </el-card> -->
    <el-card
      style="width:100%;margin-top:1rem;"
      shadow="none"
    >
      <div class="crud-group">
        <el-input
          v-model="tableParams.name"
          placeholder="请输入名称"
          style="width: 200px;"
          clearable
        />

        <el-select
          v-model="tableParams.healthSummary"
          placeholder="请选择状态"
          clearable
          style="width: 200px;"
        >
          <el-option
            v-for="item in healthSummaryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-date-picker
          v-model="tableParams.timeRange"
          type="datetimerange"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :default-time="['00:00:00','23:59:59']"
          value-format="yyyy-MM-dd HH:mm:ss"
          clearable
        />
        <el-button
          type="success"
          icon="el-icon-search"
          @click="queryServices"
        >
          搜索
        </el-button>
        <el-button
          type="warning"
          icon="el-icon-refresh-left"
          @click="resetTableParams"
        >
          重置
        </el-button>
      </div>
      <el-table
        v-loading="isTableLoading"
        :data="tableData"
      >
        <el-table-column
          prop="cmName"
          label="集群名"
        />
        <el-table-column
          prop="clusterName"
          label="子集群名"
        />
        <el-table-column
          prop="name"
          label="名称"
        />
        <el-table-column
          prop="healthSummary"
          label="状态"
        >
          <template slot-scope="scope">
            <el-tag
              :type="getStatusColor(scope.row.healthSummary)"
            >
              {{ getStatusText(scope.row.healthSummary ) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
        />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="selectedHealthChecks = JSON.parse(scope.row.healthChecks); healthChecksVisible = true"
            >详情</el-button>
          </template></el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          :current-page="tableParams.current"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="tableParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableParams.total"
          @size-change="handleTableSizeChange"
          @current-change="handleTableCurrentChange"
        />
      </div>
      <!-- <div
        class="title-row"
        style="margin-bottom:0.6rem;display: flex;"
      >
        <span class="title-row-bar" />角色状态监控
        <span style="font-size:13px; margin-left: 0.6rem;opacity: 0.8;margin-top: auto;">点击节点查看详细错误信息</span>
      </div>

      <div>
        <el-form
          :inline="true"
          label-width="220px"
        >
          <el-form-item label="查询时间:">
            <el-date-picker
              v-model="userValue"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptions"
              @change="userChange"
            />
          </el-form-item>
        </el-form>

        <div
          v-show="userStateNumsSeries.length"
          id="user"
          style="width:100%;height:270px"
        />
        <el-empty
          v-if="!userStateNumsSeries.length"
          description="暂无数据"
          style="width:100%;height:270px"
        />
      </div> -->
    </el-card>
    <el-dialog
      :visible.sync="dialogVisible"
      :before-close="handleClose"
      title="节点详情"
      width="800px"
    >
      <el-pagination
        style="margin-top: 8px;"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="detailsData.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <el-table
        v-loading="reqLoad"
        :data="detailsData.slice((currentPage - 1) * pageSize, currentPage * pageSize)"
      >
        <el-table-column
          label="服务状态"
          prop="serviceType"
          show-overflow-tooltip
        />
        <el-table-column
          label="角色名称"
          prop="roleType"
          show-overflow-tooltip
        />
        <el-table-column
          label="主机名称"
          prop="hostname"
          show-overflow-tooltip
        />
        <el-table-column
          label="健康状态"
          prop="hostname"
          show-overflow-tooltip
        />
        <el-table-column
          label="健康检查"
          prop="healthChecks"
          show-overflow-tooltip
        />
        <el-table-column
          label="异常个数"
          prop="errorNum"
          sortable
          show-overflow-tooltip
        />
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="detail(scope.row)"
            >健康检查详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="handleClose"
        >取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="dialogVisible1"
      :before-close="handleClose1"
      title="健康检查详情"
      append-to-body
      width="800px"
    >
      <el-pagination
        style="margin-top: 8px;"
        :current-page="currentPage1"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :page-size="pageSize1"
        layout="total, sizes, prev, pager, next, jumper"
        :total="checkData.length"
        @size-change="handleSizeChange1"
        @current-change="handleCurrentChange1"
      />
      <el-table
        :data="checkData.slice((currentPage1 - 1) * pageSize1, currentPage1 * pageSize1)"
        empty-text="请求数据中"
      >
        <el-table-column
          label="名称"
          prop="name"
          show-overflow-tooltip
        />
        <el-table-column
          label="状态"
          prop="summary"
          sortable
          show-overflow-tooltip
        />
        <el-table-column
          label="suppressed"
          prop="suppressed"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            {{ scope.row.suppressed }}
          </template>
        </el-table-column>
      </el-table>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="handleClose1"
        >取消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :visible.sync="healthChecksVisible"
      title="健康检查详情"
      append-to-body
      width="800px"
    >
      <el-table :data="selectedHealthChecks">
        <el-table-column
          label="角色"
          prop="name"
          show-overflow-tooltip
        />
        <el-table-column
          label="状态"
          prop="summary"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <el-tag
              :type="getStatusColor(scope.row.summary)"
            >
              {{ getStatusText(scope.row.summary ) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="说明"
          prop="explanation"
        />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import monitor from '@/api/monitor/monitor'
import * as echarts from 'echarts'
import dateUtil from '@/utils/date'
import { scrollableTooltip } from '@/utils/chartOption'
import elementResizeDetectorMaker from 'element-resize-detector'

export default {
  name: 'State',
  // mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      // fileURL: fileURL,
      tableData: [],
      healthChecksVisible: false,
      selectedHealthChecks: [],
      isTableLoading: false,
      tableParams: {
        current: 1,
        size: 10,
        total: 0,
        name: '',
        healthSummary: '',
        timeRange: []
      },
      healthSummaryOptions: [
        { value: 'GOOD', label: '正常' },
        { value: 'BAD', label: '异常' },
        { value: 'CONCERNING', label: '警告' }
      ],
      form: {
        dataTime: '2021-10-14 14：39：00',
        centerId: 'tzCenter',
        clusterFlag: '',
        centerList: [{ 'key': 'tzCenter', 'value': '上海唐镇' }, { 'key': 'wgCenter', 'value': '上海万国' }, { 'key': 'bjCenter', 'value': '北京信总' }],
        cmList: [],
        cmFlag: ''
      },
      monitorType: 'YARN',
      centerCluster: { centerClusters: [] },
      stateInfoList: [],
      hostYarnInfoList: [],
      hostImpalaInfoList: [],
      yarnStateHistory: [],
      impalaStateHistory: [],
      stateHistory: [],
      hostList: [],
      flag: false,
      list: ['YARN', 'IMPALA'],
      cluster: '',
      service: [],
      historyList: [],
      errRes: '',
      typeList: [],
      typeData: [],
      clustData: [],
      serviceStateNumsX: [],
      serviceStateName: [],
      serviceStateNumsSeries: [],
      userStateNumsX: [],
      userStateName: [],
      userStateNumsSeries: [],
      dialogVisible: false,
      dialogVisible1: false,
      detailsData: [],
      checkData: [],
      currentPage: 1, // 当前页码
      total: 20, // 总条数
      pageSize: 10, // 每页的数据条数
      reqLoad: false,
      currentPage1: 1, // 当前页码
      total1: 20, // 总条数
      pageSize1: 10, // 每页的数据条数
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      serviceValue: [
        dateUtil.getPastTimeFull(1), dateUtil.getNowDateFull()
      ],
      serviceStart: dateUtil.getPastTimeFull(1),
      serviceEnd: dateUtil.getNowDateFull(),
      userValue: [
        dateUtil.getPastTimeFull(1), dateUtil.getNowDateFull()
      ],
      userStart: dateUtil.getPastTimeFull(1),
      userEnd: dateUtil.getNowDateFull()
    }
  },
  async created() {
    await this.selAllCm()
    if (this.$route.query.clusterIndex) {
      const index = this.$route.query.clusterIndex
      this.form.cmFlag = this.form.cmList[index].cmFlag
      this.form.clusterFlag = this.form.cmList[index].clusterFlag
    }
    this.selClusterInfos()
    this.queryServices()
    // this.crud.previewcrud('状态监控')
  },
  methods: {
    async queryServices(resetPage = false) {
      this.isTableLoading = true
      if (resetPage) {
        this.tableParams.current = 1
      }
      if (!this.tableParams.timeRange) {
        this.tableParams.timeRange = []
      }
      const params = {
        cmFlag: this.form.cmFlag,
        clusterFlag: this.form.clusterFlag,
        startTime: this.tableParams.timeRange[0] || '',
        endTime: this.tableParams.timeRange[1] || '',
        ...this.tableParams
      }
      const res = await monitor.queryServices(params)
      this.tableData = res.content
      this.tableParams.total = res.totalElements
      this.isTableLoading = false
    },
    async selAllCm() {
      const reqData = { 'centerId': '1' }
      const res = await monitor.selAllCm(reqData)
      this.form.cmList = res
      this.form.cmFlag = res[0].cmFlag
      this.form.clusterFlag = res[0].clusterFlag
      if (this.$route.query.cmFlag !== undefined) {
        this.form.cmFlag = this.$route.query.cmFlag
      }
    },
    selectCm() {
      this.form.clusterFlag = this.form.cmList.find(item => item.cmFlag === this.form.cmFlag).clusterFlag
      this.selClusterInfos()
      this.queryServices()
    },
    selClusterInfos() {
      this.getTable()
    },
    childrenClu() {
      this.getTable()
    },
    getTable() {
      this.typeData = []
      this.clustData = []
      const obj = { 'cmFlag': this.form.cmFlag, 'clusterFlag': this.form.clusterFlag }
      this.typeList = []
      monitor.tableList(obj).then((res) => {
        res.forEach((item) => {
          this.typeData.push(item.type)
          const obj = {
            name: item.type,
            value: parseInt(item.bad) > 0 ? 2 : parseInt(item.conc) ? 1 : 0
          }
          if (parseInt(item.bad) > 0 || parseInt(item.conc) > 0) {
            this.typeList.push(item.type)
          }
          this.clustData.push(obj)
        })
        // this.serviceStatus()
        this.userStatus()
      })
    },
    checkType() {
      if (this.typeList.length > 0) {
        // this.serviceStatus()
        this.userStatus()
      } else if (this.typeList.length === 0) {
        this.serviceStateName = []
        this.serviceStateNumsSeries = []
        this.serviceStateNumsX = []
        this.userStateName = []
        this.userStateNumsSeries = []
        this.userStateNumsX = []
        // this.initServiceState()
        // this.userState()
      }
    },
    serviceStatus() {
      this.serviceStateName = []
      this.serviceStateNumsSeries = []
      const obj = { 'cmFlag': this.form.cmFlag, 'clusterFlag': this.form.clusterFlag, 'serviceType': this.typeList, startTime: this.serviceStart, endTime: this.serviceEnd }
      monitor.serviceStatus(obj).then((res) => {
        res.forEach((item) => {
          const arr = []
          this.serviceStateNumsX = []
          this.serviceStateName.push(item.name)
          item.stateCountInfoList.forEach((val) => {
            this.serviceStateNumsX.push(val.ct)
            arr.push(val.bad * 1 + val.conc * 1)
          })
          const obj = { name: item.name, type: 'line', data: arr }
          this.serviceStateNumsSeries.push(obj)
        })
        this.initServiceState()
      })
    },
    initServiceState() {
      var myChart = echarts.init(
        document.getElementById('service')
      )
      var option
      option = {
        legend: {
          type: 'scroll',
          data: this.serviceStateName
        },
        tooltip: scrollableTooltip,
        calculable: true,
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.serviceStateNumsX
        },
        yAxis: {
          type: 'value',
          max: 10,
          minInterval: 1
        },
        series: this.serviceStateNumsSeries
      }
      option && myChart.setOption(option, true)
      const erd = elementResizeDetectorMaker()
      erd.listenTo(document.getElementById('service'), (element) => {
        myChart.resize()
      })
    },
    userStatus() {
      this.userStateName = []
      this.userStateNumsSeries = []
      const obj = { 'cmFlag': this.form.cmFlag, 'clusterFlag': this.form.clusterFlag, 'serviceType': this.typeList, startTime: this.userStart, endTime: this.userEnd }
      monitor.userStatus(obj).then((res) => {
        res.forEach((item) => {
          const arr = []
          this.userStateNumsX = []
          this.userStateName.push(item.roleType)
          item.stateCountInfoList.forEach((val) => {
            this.userStateNumsX.push(val.ct)
            arr.push(val.bad * 1 + val.conc * 1)
          })
          const obj = { name: item.roleType, type: 'line', data: arr }
          this.userStateNumsSeries.push(obj)
        })
        // this.userState()
      })
    },
    // userState() {
    //   var myChart = echarts.init(
    //     document.getElementById('user')
    //   )
    //   var option
    //   option = {
    //     legend: {
    //       type: 'scroll',
    //       data: this.userStateName,
    //       left: '30%'
    //     },
    //     tooltip: scrollableTooltip,
    //     calculable: true,
    //     xAxis: {
    //       type: 'category',
    //       boundaryGap: false,
    //       data: this.userStateNumsX
    //     },
    //     yAxis: {
    //       type: 'value'
    //     },
    //     series: this.userStateNumsSeries
    //   }
    //   option && myChart.setOption(option, true)
    //   const erd = elementResizeDetectorMaker()
    //   erd.listenTo(document.getElementById('user'), (element) => {
    //     myChart.resize()
    //   })
    //   const that = this
    //   myChart.on('click', function (val) {
    //     that.dialogVisible = true
    //     that.reqLoad = true
    //     that.detailsData = []
    //     const obj = { 'cmFlag': that.form.cmFlag, 'clusterFlag': that.form.clusterFlag, 'serviceType': that.typeList, 'createTime': val.name }
    //     monitor.getFormData(obj).then((res) => {
    //       res.forEach((item) => {
    //         const arr = []
    //         JSON.parse(item.healthChecks).forEach((val) => {
    //           if (val.summary === 'BAD' || val.summary === 'CONCERNING') {
    //             arr.push(val)
    //             item.errorNum = arr.length
    //           }
    //         })
    //       })
    //       that.reqLoad = false
    //       that.detailsData = res
    //     })
    //   })
    // },
    handleClose() {
      this.dialogVisible = false
    },
    handleClose1() {
      this.dialogVisible1 = false
    },
    detail(row) {
      this.checkData = JSON.parse(row.healthChecks)
      this.dialogVisible1 = true
    },
    handleSizeChange(val) {
      this.currentPage = 1
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    handleSizeChange1(val) {
      this.currentPage1 = 1
      this.pageSize1 = val
    },
    handleCurrentChange1(val) {
      this.currentPage1 = val
    },
    serviceChange() {
      if (this.serviceValue) {
        this.serviceStart = this.serviceValue[0]
        this.serviceEnd = this.serviceValue[1]
      } else if (this.serviceValue == null) {
        this.serviceStart = ''
        this.serviceEnd = ''
      }
      this.serviceStatus()
    },
    userChange() {
      if (this.userValue) {
        this.userStart = this.userValue[0]
        this.userEnd = this.userValue[1]
      } else if (this.userValue == null) {
        this.userStart = ''
        this.userEnd = ''
      }
      this.userStatus()
    },
    getStatusText(text) {
      switch (text) {
        case 'GOOD':
          return '正常'
        case 'BAD':
          return '异常'
        case 'CONCERNING':
          return '告警'
        case 'DISABLED':
          return '禁用'
        default:
          return '未知'
      }
    },
    getStatusColor(text) {
      switch (text) {
        case 'GOOD':
          return 'success'
        case 'BAD':
          return 'danger'
        case 'CONCERNING':
          return 'warning'
        case 'DISABLED':
          return 'info'
        default:
          return ''
      }
    },
    resetTableParams() {
      this.tableParams = {
        current: 1,
        size: 10,
        total: 0,
        name: '',
        healthSummary: ''
      }
      this.queryServices()
    },
    handleTableSizeChange(val) {
      this.tableParams.size = val
      this.queryServices(true)
    },
    handleTableCurrentChange(val) {
      this.tableParams.current = val
      this.queryServices()
    }
  }
}
</script>

<style scoped>
.el-button--small {
  padding: 6px 10px;
}

.UrlBox {
  color: #4b06ee;
  margin-left: 10px;
}

.cardBox {
  margin-top: 10px;
  font-size: 12px;
  width: 120px;
  text-align: center;

}

.total {
  font-size: 24px;
  color: white;
  border: 1px solid #dedede;
  box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.04);
  border-radius: 5px;
  text-align: center;
  background-color: #409EFF;
  width: 80%;
  margin-left: 10px;
}

.error {
  font-size: 24px;
  color: white;
  border: 1px solid #dedede;
  box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.04);
  border-radius: 25%;
  text-align: center;
  background-color: #F56C6C;
  width: 80%;
  margin-left: 10px;
}

.warn {
  font-size: 24px;
  color: white;
  border: 1px solid #dedede;
  box-shadow: 0px 5px 5px 0px rgba(0, 0, 0, 0.04);
  border-radius: 25%;
  text-align: center;
  background-color: orange;
  width: 80%;
  margin-left: 10px;
}

.el-card {
  box-shadow: none;
}
</style>
